import { ProTable, type ProColumns } from '@/components/Pro';
import { statisticWorkStatusControllerGetDateWorkStatusPage } from '@/services/ess/statisticWorkstatus';
import { fetchDictInfo } from '@/utils';
import { deviceTreeData } from '@/utils/formatterTree';
import { useIntl } from '@umijs/max';
import dayjs from 'dayjs';
import _ from 'lodash';
import moment from 'moment';
import React, { ReactNode, useRef, useState } from 'react';
import './Common.less';

type IProps = {
  treeData: deviceTreeData[];
  // 修改导出数据
  changeReportData: (data: any) => void;
};
const DayReport: React.FC<IProps> = (props) => {
  const intl = useIntl();
  const tableRef = useRef(null);
  const { treeData, changeReportData } = props;
  const [workDate, setWorkDate] = useState(dayjs().subtract(1, 'day'));
  const [stationToken, changeStationToken] = useState(true);
  const [cascaderVal, setCascaderVal] = useState(treeData[0].uniqueId);
  const [code, setCode] = useState(treeData[0].stationId);
  const [areaIdList, setAreaIdList] = useState(null);
  const [dataType, setDataType] = useState('1');
  const columns: ProColumns[] = [
    {
      valueType: 'index',
      dataIndex: 'index',
      title: intl.formatMessage({ id: 'batteryVoltage.tableNo' }),
      width: 60,
    },
    {
      title: intl.formatMessage({ id: 'statistics.common.period' }),
      dataIndex: 'timeRange',
      hideInSearch: true,
      width: 200,
      render: (_, record) => {
        return (
          <span>
            {record.startTime}-{record.endTime}
          </span>
        );
      },
    },
    {
      title: intl.formatMessage({ id: 'statistics.income.select' }),
      hideInTable: true,
      dataIndex: 'date',
      valueType: 'date',
      initialValue: dayjs().subtract(1, 'day'),
      fieldProps: {
        allowClear: false,
        value: workDate,
        disabledDate: (current) => {
          return current && current > moment().endOf('day');
        },
        onChange: (e: ReactNode, dateString: string) => {
          setWorkDate(e);
          changeReportData({
            dateType: 'day',
            date: dateString,
            dataType: dataType,
            code: code,
            areaIdList: areaIdList,
          });
        },
      },
    },
    // 🐱分区维度
    {
      title: intl.formatMessage({ id: 'statistics.work.dimensions' }),
      dataIndex: 'areaIdList',
      hideInTable: true,
      valueType: 'cascader',
      fieldProps: {
        changeOnSelect: true,
        allowClear: false,
        value: cascaderVal,
        options: treeData,
        fieldNames: {
          label: 'deviceName',
          value: 'uniqueId',
          children: 'subDevices',
        },
        onChange: (e: string[], params: API.DeviceTreeVO[]) => {
          setCascaderVal(e);
          // 分区模块
          const selectedItem = _.last(params);
          setDataType(
            selectedItem?.nodeType === 'ROOT' ? '1' : selectedItem?.nodeType === 'AREA' ? '3' : '2',
          );
          setCode(
            selectedItem?.nodeType === 'ROOT' ? selectedItem?.stationId : selectedItem?.deviceCode,
          );
          setAreaIdList(selectedItem?.nodeType === 'AREA' ? selectedItem?.areaId : null);
          changeReportData({
            dateType: 'day',
            date: dayjs(workDate).format('YYYY-MM-DD'),
            dataType:
              selectedItem?.nodeType === 'ROOT'
                ? '1'
                : selectedItem?.nodeType === 'AREA'
                ? '3'
                : '2',
            code:
              selectedItem?.nodeType === 'ROOT'
                ? selectedItem?.stationId
                : selectedItem?.deviceCode,
            areaIdList: selectedItem?.nodeType === 'AREA' ? selectedItem?.areaId : null,
          });
        },
      },
    },

    {
      title: intl.formatMessage({ id: 'statistics.work.work' }),
      dataIndex: 'workState',
      hideInSearch: true,
      valueType: 'select',
      width: 90,
      request: () => fetchDictInfo(100036),
    },
    {
      title: intl.formatMessage({ id: 'statistics.common.alStack' }),
      dataIndex: 'locationName',
      hideInSearch: true,
      hideInTable: stationToken,
    },
    {
      title: intl.formatMessage({ id: 'statistics.common.duration' }),
      dataIndex: 'durationTime',
      width: 100,
      hideInSearch: true,
    },
    {
      title: intl.formatMessage({ id: 'statistics.analyze.maxCurrentTime' }),
      dataIndex: 'largeCurrentTime',
      width: 100,
      hideInSearch: true,
    },
    {
      title: intl.formatMessage({ id: 'statistics.analyze.minCurrentTime' }),
      dataIndex: 'lowCurrentTime',
      width: 100,
      hideInSearch: true,
    },
    {
      title: `${intl.formatMessage({ id: 'statistics.common.discharge' })}(kWh)`,
      dataIndex: 'dischargeEnergy',
      hideInSearch: true,
    },
    {
      title: `${intl.formatMessage({ id: 'statistics.common.charge' })}(kWh)`,
      dataIndex: 'chargeEnergy',
      hideInSearch: true,
    },
    {
      title: `${intl.formatMessage({ id: 'batteryVoltage.safe.onGrid' })}(kWh)`,
      dataIndex: 'pocOnGridEnergy',
      hideInSearch: true,
    },
    {
      title: `${intl.formatMessage({ id: 'batteryVoltage.safe.offGrid' })}(kWh)`,
      dataIndex: 'pocOffGridEnergy',
      hideInSearch: true,
    },
  ];
  return (
    <>
      <ProTable
        headerTitle=" "
        style={{ position: 'relative', zIndex: '10' }}
        actionRef={tableRef}
        onReset={() => {
          setWorkDate(dayjs().subtract(1, 'day'));
          setDataType('1');
          changeReportData({
            dateType: 'day',
            date: dayjs().subtract(1, 'day').format('YYYY-MM-DD'),
            dataType: '1',
            code: treeData[0].stationId,
            areaIdList: null,
          });
          setAreaIdList(null);
          setCode(treeData[0].stationId);
          setCascaderVal(treeData[0].uniqueId);
          tableRef?.current?.reset();
        }}
        columns={columns}
        request={async (values) => {
          changeStationToken(dataType === '1');
          const params = {
            current: values?.current,
            pageSize: values?.pageSize,
            dataType: dataType,
            date: dayjs(workDate).format('YYYY-MM-DD'),
            code: dataType !== '3' ? code : '',
            areaIdList: areaIdList,
          };
          return await statisticWorkStatusControllerGetDateWorkStatusPage(params);
        }}
        search={{
          className: 'searchPosInline',
        }}
        toolbar={{
          className: 'toobalrZindex',
          actions: [
            // eslint-disable-next-line react/button-has-type
          ],
        }}
      ></ProTable>
    </>
  );
};

export default DayReport;
